import request from './request'

export interface Customer {
  id: number
  username: string
  email: string
  first_name: string
  last_name: string
  full_name: string
  is_active: boolean
  date_joined: string
  last_login: string | null
  profile: {
    phone: string
    avatar: string | null
    company: string
    address_line1: string
    address_line2: string
    city: string
    state: string
    postal_code: string
    country: string
    total_orders: number
    total_spent: string
    preferred_language: string
    newsletter_subscribed: boolean
    created_at: string
    updated_at: string
  }
  addresses?: Array<{
    id: number
    first_name: string
    last_name: string
    company: string
    address_line1: string
    address_line2: string
    city: string
    state: string
    postal_code: string
    country: string
    phone: string
    is_default: boolean
    created_at: string
    updated_at: string
  }>
}

export interface CustomerListResponse {
  count: number
  next: string | null
  previous: string | null
  results: Customer[]
}

export interface CustomerQueryParams {
  page?: number
  page_size?: number
  search?: string
  is_active?: boolean
  newsletter_subscribed?: boolean
  ordering?: string
}

/**
 * 获取客户列表
 */
export function getCustomers(params?: CustomerQueryParams) {
  return request<CustomerListResponse>({
    url: '/customers/',
    method: 'get',
    params
  })
}

/**
 * 获取客户详情
 */
export function getCustomerDetail(id: number) {
  return request<Customer>({
    url: `/customers/${id}/`,
    method: 'get'
  })
}

/**
 * 更新客户信息
 */
export function updateCustomer(id: number, data: Partial<Customer> & { profile?: Partial<Customer['profile']> }) {
  return request<Customer>({
    url: `/customers/${id}/`,
    method: 'patch',
    data
  })
}

/**
 * 切换客户激活状态
 */
export function toggleCustomerActive(id: number) {
  return request<{ message: string; is_active: boolean }>({
    url: `/customers/${id}/toggle_active/`,
    method: 'patch'
  })
}

/**
 * 重置客户密码
 */
export function resetCustomerPassword(id: number, new_password: string) {
  return request<{ message: string }>({
    url: `/customers/${id}/reset_password/`,
    method: 'post',
    data: { new_password }
  })
}

/**
 * 删除客户（软删除）
 */
export function deleteCustomer(id: number) {
  return request({
    url: `/customers/${id}/`,
    method: 'delete'
  })
}

/**
 * 获取客户统计信息
 */
export function getCustomerStats() {
  return request<{
    total_customers: number
    active_customers: number
    newsletter_subscribers: number
    total_orders: number
    total_revenue: string
  }>({
    url: '/customers/stats/',
    method: 'get'
  })
}
